import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(Router)

const router = new Router({
    mode: 'history',
    routes
})


//路由守卫
// todo 测试中，先屏蔽掉
router.beforeEach((to, from, next) => {
    NProgress.start();
    if (to.meta.auth === true) {
        // 跳转的页面需要验证
        if (getToken()) {
            // 有token
            next();
            NProgress.done();
        } else {
            // 没有token
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            });
        }
    } else {
        if (to.name === 'login' || to.name === 'register') {
            // 跳转的页面为登录注册页
            // 如果有token，则自动跳到home
            if (getToken()) {
                next('/');
                NProgress.done();
            } else {
                // 如果没有token，可以跳转过去
                next();
            }
        }
        next();
    }
});

router.afterEach(() => {
    NProgress.done();
})

export default router;